package zhao.ben.quan.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;
import zhao.ben.quan.constant.MessageConstant;
import zhao.ben.quan.constant.RedisConstant;
import zhao.ben.quan.entity.PageResult;
import zhao.ben.quan.entity.QueryPageBean;
import zhao.ben.quan.entity.Result;
import zhao.ben.quan.pojo.Setmeal;
import zhao.ben.quan.service.SetmealService;
import zhao.ben.quan.utils.QiniuUtils;

import java.io.IOException;
import java.util.UUID;

/**
 * 体检套餐管理
 */
@RestController //@Controller+@ResponseBody
@RequestMapping("/setmeal")
public class SetmealController {

    //使用JedisPool操作redis服务
    @Autowired
    private JedisPool jedisPool;

    @Reference//去提供者查找接口
    private SetmealService setmealService;

    //文件上传
    @RequestMapping("/upload")  //action="/setmeal/upload.do"
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
//        System.out.println(imgFile);

        //拿到图片原始名称
        String originalFilename = imgFile.getOriginalFilename();//abc.jpg

        int index = originalFilename.lastIndexOf(".");//获取.的位置

        String extention = originalFilename.substring(index - 1);//拿到.jpg

        //生成随机的uuid字符串
        String fileName = UUID.randomUUID().toString()+extention;

        try {
            //将文件上传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            //将上传图片名称存入Redis，基于Redis的Set集合存储
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);//上传成功

    }


    //添加套餐项
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer [] checkgroupIds){
        try {
            setmealService.add(setmeal,checkgroupIds);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);//新增成功
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);//新增失败
        }
    }


    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
       return setmealService.findPage(queryPageBean);
    }

}
